package hydrap2p.manager;

import java.util.LinkedList;
import java.util.List;

import hydrap2p.ServiceLocation;
import hydrap2p.servicemanager.ServiceListener;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;

public class ServiceListenerEvents {
	private ServiceListener.Iface connection;
	private List<ListenerEvent> events;
	
	public ServiceListenerEvents(ServiceListener.Iface connection)
	{
		this.connection=connection;
		this.events=new LinkedList<ListenerEvent>();
	}
	public ServiceListenerEvents(ServiceLocation location) throws TTransportException
	{
		TTransport transport=new TSocket(location.address,location.port);
		transport.open();
		this.connection=new ServiceListener.Client(new TBinaryProtocol(transport));;
		this.events=new LinkedList<ListenerEvent>();
	}
	
	private abstract class ListenerEvent
	{
		public abstract void doIt() throws TException;
	}
	private class ListenerEventNewService extends ListenerEvent
	{
		private String name;
		private ServiceLocation location;
		public ListenerEventNewService( String servicename, ServiceLocation location) {
			this.name=servicename;
			this.location=location;
		}
		public void doIt() throws TException
		{
			connection.newService(name, location);
		}
	}
	private class ListenerEventDelService extends ListenerEvent
	{
		private String name;
		public ListenerEventDelService(String servicename) {
			this.name=servicename;
		}
		public void doIt() throws TException
		{
			connection.delService(name);
		}
	}
	
	public void newService(String name, ServiceLocation location)
	{
		synchronized(events)
		{
			events.add(new ListenerEventNewService(name,location));
		}
	}
	
	public void delService(String name)
	{
		synchronized(events)
		{
			events.add(new ListenerEventDelService(name));
		}
	}
	
	public void process() throws TException
	{
		while (events.size()>0)
		{
			synchronized(events)
			{
				if (events.size()>0)
				{
					ListenerEvent event=events.remove(0);
					event.doIt();
				}
			}
		}
	}
}
